package com.ljfiction.book.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.ljfiction.book.Baner.ReadDuanBean;
import com.ljfiction.book.MyView.ContainsEmojiEditText;
import com.ljfiction.book.MyView.DividerItemDecoration;
import com.ljfiction.book.R;
import com.ljfiction.book.adapter.ReadDuanpingAdapter;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.http.SoftHideKeyBoardUtil;
import com.ljfiction.book.http.UserManageBean;
import com.ljfiction.book.tools.EventTool;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.Tool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jaydenxiao.com.expandabletextview.ExpandableTextView;
import okhttp3.Call;
import okhttp3.Response;

public class ReadDuanpingActivity extends BaseActivity {

    @BindView(R.id.chaptertitle_readduanping)
    TextView chaptertitleReadduanping;
    @BindView(R.id.closeimage)
    ImageView closeimage;
    @BindView(R.id.chaptertext)
    ExpandableTextView chaptertext;
    @BindView(R.id.danmunum)
    TextView danmunum;
    @BindView(R.id.readduanpingrecycle)
    RecyclerView readduanpingrecycle;
    @BindView(R.id.send)
    TextView send;
    @BindView(R.id.tocomment)
    ContainsEmojiEditText tocomment;
    @BindView(R.id.refteshduanping)
    SmartRefreshLayout refteshduanping;

    private ReadDuanpingAdapter adpterread;
    private List<ReadDuanBean.DataBean.ListBean> list = new ArrayList<>();
    private int page = 1;
    private ReadDuanBean readDuanBean;
    private String uuid;
    private Intent intent;
    private int chapterId;
    private String bookId;
    private String bookTitle;
    private String chapterTitle;
    private boolean isPinglun = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_read_duanping);
        ButterKnife.bind(this);
        SoftHideKeyBoardUtil.assistActivity(this);
        chaptertext.setText(getIntent().getStringExtra("chaptertext"));
        chapterId = getIntent().getIntExtra("chapterId", 1);
        bookId = getIntent().getStringExtra("bookId");
        bookTitle = getIntent().getStringExtra("bookName");
        uuid = getIntent().getStringExtra("uuid");
        chapterTitle = getIntent().getStringExtra("chapteTitle");
        chaptertitleReadduanping.setText(chapterTitle);
        intent = new Intent(this, UserCenterActivity.class);
        intView();
        intData();
    }

    private void intData() {
        OkHttpUtils.get(HttpManager.IP + "/pcomm-getParagraphcommentpid/" + uuid + "/" + page)

                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        try {
                            readDuanBean = gson.fromJson(s, ReadDuanBean.class);
                            if (readDuanBean.getReturnCode() == 200) {
                                refteshduanping.finishRefresh();
                                refteshduanping.finishLoadMore();
                                list.addAll(readDuanBean.getData().getList());
                                adpterread.notifyDataSetChanged();
                            }
                            danmunum.setText(String.valueOf(list.size()));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void intView() {
        adpterread = new ReadDuanpingAdapter(R.layout.readduanping_item, list);
        adpterread.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(final BaseQuickAdapter adapter, final View view, final int position) {
                switch (view.getId()) {

                    case R.id.zanimage:
                        if (!UserManageBean.isLogin(ReadDuanpingActivity.this)) {
                            return;
                        }
                        OkHttpUtils.post(HttpManager.IP + "/paragraphcomment-GiveThumbs")

                                .params("paragraphcommentid", String.valueOf(list.get(position).getId()))
                                .execute(new StringCallback() {
                                    @Override
                                    public void onSuccess(String s, Call call, Response response) {
                                        try {
                                            JSONObject jsonObject = new JSONObject(s);
                                            if (jsonObject.getInt("returnCode") == 200) {

                                                if (list.get(position).getIsthumbs() == 0) {
                                                    list.get(position).setIsthumbs(1);
                                                    list.get(position).setThumbsCount(list.get(position).getThumbsCount() + 1);
                                                    adapter.notifyDataSetChanged();
                                                } else {
                                                    list.get(position).setIsthumbs(0);
                                                    list.get(position).setThumbsCount(list.get(position).getThumbsCount() - 1);
                                                    adapter.notifyDataSetChanged();
                                                }
                                            }else if (jsonObject.getInt("returnCode") == 400){
                                                Intent intent=new Intent(ReadDuanpingActivity.this, LoginActivity.class);
                                                startActivity(intent);
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }

                                    }
                                });
                        break;
                    case R.id.myshuping_read:
                        intent.putExtra("userId", String.valueOf(list.get(position).getUserId()));
                        startActivity(intent);
                        break;
                }
            }
        });
        readduanpingrecycle.setLayoutManager(new LinearLayoutManager(this));
        readduanpingrecycle.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        readduanpingrecycle.setAdapter(adpterread);
        refteshduanping.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                if (readDuanBean.getData().isIsLastPage()){
                    refreshlayout.finishLoadMore();
                    refteshduanping.setEnableLoadMore(false);
                }else {
                    page++;
                    intData();

                }
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                list.clear();
                refteshduanping.setEnableLoadMore(true);
                intData();
            }
        });
        tocomment.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (String.valueOf(editable).length() >= 100) {
                    showToast("评论内容不能超过100个字");
                }
            }
        });
    }

    //监听返回键
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isPinglun) {
                setResult(8);
            }
            goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @OnClick({R.id.closeimage, R.id.send})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.closeimage:
                if (isPinglun) {
                    setResult(8);
                }
                goBack();
                break;
            case R.id.send:
                if (tocomment.getText().toString().equals("")) {
                    showToast("评论内容不能为空");
                } else if (!UserManageBean.isLogin(ReadDuanpingActivity.this)) {
                    return;
                } else {
                    OkHttpUtils.post(HttpManager.IP + "/pcomm-addParagraphcomment")

                            .params("pid", uuid)
                            .params("bookId", bookId)
                            .params("bookName", bookTitle)
                            .params("userName", UserManageBean.userBean.getPseudonym())
                            .params("commentContext", tocomment.getText().toString())
                            .params("chapterId", String.valueOf(chapterId))
                            .params("chapterName", chapterTitle)
                            .execute(new StringCallback() {
                                @Override
                                public void onSuccess(String s, Call call, Response response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(s);
                                        if (jsonObject.getInt("returnCode") == 200) {
                                            tocomment.setText("");
                                            Tool.hideKeybard(ReadDuanpingActivity.this);
                                            isPinglun = true;
                                            list.clear();
                                            page=1;
                                            intData();
                                        }else if (jsonObject.getInt("returnCode")==400){
                                            Intent intent=new Intent(ReadDuanpingActivity.this,LoginActivity.class);
                                            startActivity(intent);
                                        }
                                        showToast(jsonObject.getString("msg"));
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                }
                break;
        }
    }

}
